<?php

namespace App\Controller\AdminApi;

use App\Base\BaseForm;
use App\Repository\MoneyPayOrderRepository;
use App\Repository\OrderCancelRepository as Repository;
use App\Repository\AdminMenuRepository;
use App\Service\PayService;
use Doctrine\ODM\MongoDB\DocumentManager;
use App\Base\IRI;
use Symfony\Component\HttpFoundation\Request;
use App\Base\BaseController4Admin;
use App\Entity\OrderCancel as Entity;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/admin/")
 */
class OrderCancelAdminApiController extends BaseController4Admin
{
    public $noDelete = [];
    public $entityName = "OrderCancel";
    public $limit = 10;

    /**
     * @Route("OrderCancel/form",name="OrderCancelForm")
     */
    public function form(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $entity = $repository->find($data["id"]??0);
        if (!$entity) {$entity = new Entity();}
        $BaseForm = new BaseForm(Entity::class);
        //表单选项

        $entity = $this->toArray($entity);
        $BaseForm->setEntity($entity);
        $data = array(
            "title" => "创建表单",
            "show"   => $BaseForm->createForm(),
            "isAdd"   => true,
        );
        return $this->json_out(1,"OK",$data);
    }

    /**
     * @Route("OrderCancel/submit",name="OrderCancelSubmit",methods={"POST"})
     */
    public function submit(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $entity = $repository->find($data["id"]?:0);
        if (!$entity) {$entity = new  Entity();}
        /**@var $OrderCancel Entity*/
        $OrderCancel = $this->updateEntity($data,Entity::class,$entity);
        $this->myEm()->persist($OrderCancel);$this->myEm()->flush();
        return $this->js_out("保存成功",$this->generateUrl("OrderCancelLists",[]));
    }

    /**
     * @Route("OrderCancel/list",name="OrderCancelGetList")
     */
    public function getList(DocumentManager $documentManager)
    {
        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $tools = array();
        $page = $data["page"]??1;
        $per_page   = $this->limit;
        $rep = $documentManager->getRepository(Entity::class);
        $condition=[];
        if($where = $data['_where']??[])$condition = createWhere4MongoDB($where);
        if($search = $data['_search']??[])$condition['$and'] = createSearch4MongoDB($search,["id"],"or");
        if(!$order = $data["_order"]??[]){$order = ["id"=>"DESC"];}
        $list = $rep->findBy($condition,$order,$per_page,$per_page * $page - $per_page);
        $re = [];
        foreach ($list as $row) {
            $orderInfo = $row->getOrders()->getInfo();
            $payType = $row->getOrders()->getPayType() == 100?"微信支付":"余额支付";
            $re[] = [
                "id"=>$row->getId(),
                "user"=>$row->getUser()->getName()."(".$row->getUser()->getPhone().")",
                "orders"=>$orderInfo["oil"]."-".$orderInfo["gun"]."实付：{$row->getOrders()->getPayReal()}，【{$payType}】",
                "createAt"=>$row->getCreateAt(),
                "status"=>$row->getStatus()?'已处理':"未处理"
            ];
        }
//        $list= $this->normalize($list);
        $qb = $documentManager->createQueryBuilder(Entity::class);
        $total = $qb->setQueryArray($condition)->count()->getQuery()->execute();
        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl("OrderCancelTools"),
            "addUrl"=>$this->generateUrl("OrderCancelPreAdd"),
        );
        $this->clearGroups();
        $config = getEntityAnnotationData(Entity::class);
        $data = array(
            'en'     => "OrderCancel",
            'title'     => "列表",
            'header'     => ["id","user","orders","createAt","status"],
            "tools"     => $tools,
            'urls'      => $urls,
            "config"    => $config,
            'lists'     => $re,
            "page"      =>['total'=>$total,"limit"=>$per_page,"page"=>$page*1],
        );
        return $this->json_out(1,'OK',$data);
    }


    /**
     * @Route("OrderCancel/delete",name="OrderCancelDelete",methods={"POST"})
     */
    public function delete(Repository $repository)
    {
        $uid = $this->needToBeAdmin();
        $ids = $this->getRequestData()["ids"]??[];
        foreach ($ids as $id) {
            if (in_array($id , $this->noDelete) || in_array(0 , $this->noDelete)) {continue;}
            if ($entity= $repository->find($id)) {$this->myEm()->remove($entity);}
        }
        $this->myEm()->flush();
        return $this->json_out(1,'删除成功');
    }


    /**
     * 用于entity组件窗口选择器
     * @Route("OrderCancel/copy",name="OrderCancelCopy")
     */
    public function doCopy(Repository $repository)
    {
        $data = $this->getRequestData();
        if (!$entity = $repository->find($data["id"]??0)) {
            return $this->json_out(0,"数据丢失");
        }
        $tmp = $entity;
        $tmp = $this->toArray($tmp);
        $en = $this->serializer->denormalize($tmp,Entity::class);
        $this->myEm()->persist($en);$this->myEm()->flush();
        return $this->json_out(1,"复制成功");
    }


    /**
     * @Route("OrderCancel/search",name="OrderCancelGetList4EntitySelect")
     */
    public function getList4EntitySelect(DocumentManager $documentManager,Request $request)
    {
        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $tools = array();
        $page = $data["page"]??1;
        $per_page   = $this->limit;
        $rep = $documentManager->getRepository(Entity::class);
        $condition=[];
        if($where = $data['_where']??[])$condition = createWhere4MongoDB($where);
        if($search = $data['_search']??[])$condition['$and'] = createSearch4MongoDB($search,["id"],"or");
        if(!$order = $data["_order"]??[]){$order = ["id"=>"DESC"];}
        $list = $rep->findBy($condition,$order,$per_page,$per_page * $page - $per_page);
        $list= $this->normalize($list);
        $qb = $documentManager->createQueryBuilder(Entity::class);
        $total = $qb->setQueryArray($condition)->count()->getQuery()->execute();
        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl("OrderCancelTools"),
            "addUrl"=>$this->generateUrl("OrderCancelPreAdd"),
        );
        $config = getEntityAnnotationData(Entity::class);
        $data = array(
            'en'     => "OrderCancel",
            'title'     => "列表",
            'header'     => ["id"],
            "tools"     => $tools,
            'urls'      => $urls,
            "config"    => $config,
            'lists'     => $list,
            "page"      =>['total'=>$total,"limit"=>$per_page,"page"=>$page*1],
        );
        return $this->json_out(1,'OK',$data);
    }


    /**
     * 用于ENTITY组件选项关展示
     * @Route("OrderCancel/viewer",name="OrderCancelList4EntityViewer")
     */
    public function OrderCancelList4EntityViewer(Repository $repository)
    {
        $data = $this->getRequestData();
        $id = $data["id"]??0;
        if (!is_array($id)) {
            $id = [$id];
        }
        $re = [];
        foreach ($id as $v) {
            //分别分成iri 和 id 两种方式
            $arr = myExplodeNumbers($v);
            $realId = array_pop($arr);
            $en = $repository->find($realId);
            if (!$en) {continue;}
            $re[] = [
                "id" => $en->getId(),
                "val" => $en->getName(),
            ];
        }
        return $this->json_out(1,"OK",$re);
    }

    /**
     * 用于列表组件List
     * @Route("OrderCancel/choice",name="OrderCancelList4ListChoice")
     */
    public function OrderCancelList4ListChoice(Repository $repository)
    {
        $all = $repository->findBy(array());
        foreach ($all as $en) {
            $re[] = [
                "id" => IRI::createIRIStringFromEntity(Entity::class,$en->getId()),
                "value" => $en->getName(),
            ];
        }
        return $this->json_out(1,"OK",$re);
    }

    /**
     * 确认退款
     * @Route("OrderCancel/confirm",name="OrderCancelConfirm")
     */
    public function OrderCancelConfirm(
        Repository $repository,
        PayService $payService,
        MoneyPayOrderRepository $moneyPayOrderRepository

    )
    {
        $req = $this->getRequestData();
        $id = $req["id"]??0;
        $orderCancel = $repository->find($id);
        $order = $orderCancel->getOrders();
//        if ($order->getPayType() != 100) {
//            return $this->json_out(0,"")
//        }
//        $payOrder = $moneyPayOrderRepository->findOneBy(array("param.orderId"=>$order->getId()));
        $data = $payService->refund($order->getSn());
        return $this->json_out(1,"OK",$data);
    }
}
